<template>
    <div class="rd-upload">
        <!-- 上传记录展示 -->
        <div class="upload-record">
            <!-- 上传按钮 -->
            <div class="upload-button flex items-center space-x-10">
                <el-upload
                    :v-model:file-list="fileList"
                    class="upload-demo"
                    :auto-upload="false"
                    accept=".xlsx"
                    :on-change="handleFileUpload"
                    :show-file-list="false"
                >
                    <el-button 
                        type="primary" 
                        v-has="'upload'"
                        :loading="uploading"
                        :disabled="uploading"
                    >
                        {{ uploading ? '上传中...' : '点击上传' }}
                    </el-button>
                </el-upload>
                <el-tag
                    class="ml-4"
                    :type="selectedFile ? 'success' : 'info'"
                    effect="plain"
                >
                    {{ selectedFile ? selectedFile.name : '请上传 .xlsx 文件' }}
                </el-tag>
                <el-button 
                    class="ml-10" 
                    @click="uploadFile" 
                    v-has="'upload'"
                    :loading="uploading"
                    :disabled="uploading"
                >
                    {{ uploading ? '上传中...' : '上传文件' }}
                </el-button>
            </div>
            <el-table :data="uploadRecords">
                <el-table-column
                    v-for="item in columns"
                    :key="item.prop"
                    :prop="item.prop" 
                    :label="item.label" 
                    :width="item.width"
                    :formatter="item.formatter"
                    align="center"
                >
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button v-if="scope.row.has_return_data === 1" type="primary" size="small" @click="downloadFile(scope.row.folder_path)" v-has="'download'">下载</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import utils from '@/utils/utils.js'

export default {
    name: 'RdUpload',
    setup() {
        const { proxy } = getCurrentInstance()
        // 选中的文件
        const selectedFile = ref(null)
        // 上传记录列表
        const uploadRecords = ref([])
        // 上传文件列表
        const fileList = ref([])
        // 上传状态
        const uploading = ref(false)

        // 定义动态表格-格式
        const columns = reactive([
            {
                label: '上传ID',
                prop: 'upload_id',
                width: 200
            },
            {
                label: '文件名',
                prop: 'file_name',
                width: 200
            },
            {
                label: '上传时间',
                prop: 'upload_time',
                width: 250,
                formatter: (row, column, value) => {
                    return utils.formateDate(new Date(value))
                }
            },
            {
                label: '是否有返回数据',
                prop: 'has_return_data',
                formatter(row, column, value) {
                    return {
                        0: '否',
                        1: '是'
                    }[value]
                },
            },
            {
                label: '文件夹路径',
                prop: 'folder_path',
                width: 300
            }
        ])

        // 初始化接口调用
        onMounted(() => {
            getUploadRecords()
        })

        // 获取上传记录
        const getUploadRecords = async () => {
            try {
                const { list } = await proxy.$api.getUploadRecords()
                uploadRecords.value = list
            } catch (error) {}
        }

        // 处理文件选择
        const handleFileUpload = (file) => {
            // 确保一次只选择一个文件，覆盖之前的选择
            fileList.value = [file]
            selectedFile.value = file.raw
        }

        // 上传文件
        const uploadFile = async () => {
            if (!selectedFile.value) {
                proxy.$message.error('请选择要上传的文件')
                return
            }
            // 开始上传，显示加载状态
            uploading.value = true
            const formData = new FormData()
            formData.append('file', selectedFile.value)
            try {
                const res = await proxy.$api.uploadXlsx(formData)
                proxy.$message.success('文件上传成功')
                getUploadRecords()
                // 上传成功后清空文件选择
                fileList.value = []
                selectedFile.value = null
            } catch (error) {
                proxy.$message.error('文件上传失败')
            } finally {
                // 无论上传成功或失败，都关闭加载状态
                uploading.value = false
            }
        }

        // 下载文件
        const downloadFile = async (folderPath) => {
            // 从路径中提取 upload_id（假设 folderPath 格式为 "uploads_data/123456789"）
            const upload_id = folderPath.split('/').pop();
            const fileName = 'mis_data.csv';
            try {
                // 直接通过浏览器打开下载链接（更简单的方式）
                window.open(`http://localhost:8080/model-api/download/${upload_id}/${fileName}`);
            } catch (error) {
                proxy.$message.error(`下载失败：${error.message}`);
            }
        }

        return {
            selectedFile,
            uploadRecords,
            columns,
            fileList,
            uploading,
            getUploadRecords,
            handleFileUpload,
            uploadFile,
            downloadFile
        }
    }
}
</script>

<style scoped>
.upload-button {
    margin-bottom: 20px;
}

.upload-record {
    background-color: #ffffff;
    padding: 20px;
    border-radius: 5px;
}
.el-tag {
    height: 32px;
    line-height: 32px;
    padding: 0 16px;
}
</style>    